# import os
from flask import Flask
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_mail import Mail
from flask_sqlalchemy import SQLAlchemy

from .config import DevConfig

app = Flask(__name__)
app.config.from_object(DevConfig)

# SQLAlchemy
# 创建MySQL数据库: CREATE DATABASE flaskdb DEFAULT CHARSET utf8mb4;
# MySQL客户端使用pymysql，安装: pipenv install pymysql
# app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:root@localhost/flaskdb'  # 用户名和密码都是root
# app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# db = SQLAlchemy(app)
# bcrypt = Bcrypt(app)
# login_manager = LoginManager(app)
db = SQLAlchemy()
bcrypt = Bcrypt()
login_manager = LoginManager()
login_manager.login_message = '请登录后再访问该页面'
login_manager.login_message_category = 'info'
login_manager.login_view = 'auth.login'  # 指定访问需要登录页面时重定向的视图函数，使用蓝图

# 密码重置
# app.config['MAIL_SERVER'] = 'smtp.126.com'
# app.config['MAIL_PORT'] = 25
# app.config['MAIL_USE_TLS'] = True
# app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME')
# app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD')
# app.config['ADMIN_EMAIL'] = os.environ.get('ADMIN_EMAIL')
# mail = Mail(app)
mail = Mail()

# CSRF保护或使用Session，闪现(Flash)需要指定秘钥(SECRET_KEY)

# 生成秘钥的两种方法:
# import secrets; secrets.token_hex(24)
# import uuid; str(uuid.uuid4())

# Linux设定环境变量命令： export ${SECRET_KEY}='xxx'
# app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY') or '1761ca4a76862a97911f42eca428967208a739a849c33f88'

# 需要导入视图函数来注册路由
# from blog import views
from blog.auth.views import auth
from blog.main.views import main
from blog.post.views import post

app.register_blueprint(auth)
app.register_blueprint(main)
app.register_blueprint(post)


def create_app(config_class=DevConfig):
    # 创建应用并导入配置
    app = Flask(__name__)
    app.config.from_object(DevConfig)

    # 初始化第三方库
    db.init_app(app)
    bcrypt.init_app(app)
    login_manager.init_app(app)
    mail.init_app(app)

    from blog.auth.views import auth
    from blog.main.views import main
    from blog.post.views import post

    # 注册蓝图
    app.register_blueprint(auth)
    app.register_blueprint(main)
    app.register_blueprint(post)

    return app
